import * as types from './mutation_types'
import request from '../../../util/axios'
import { removeRefreshToken, removeToken, setToken, setRefreshToken } from '../../../util/auth'
import qs from 'qs'
import md5 from 'js-md5'

// 登录
export const login = ({ commit }, data) => {
  const param = JSON.parse(JSON.stringify(data))
  param.password = md5(param.password + 'yuyi')
  return request({
    url: '/yuyi-auth/api/oauth/token',
    method: 'post',
    meta: {
      isToken: false
    },
    data: qs.stringify(param)
  }).then((res) => {
    setToken(res.data.data.access_token)
    setRefreshToken(res.data.data.refresh_token)
    return res
  })
}

// 退出登录
export const loginOut = ({ commit }) => {
  return request({
    url: '/yuyi-auth/api/oauth/logout',
    method: 'delete'
  }).then((res) => {
    removeToken()
    removeRefreshToken()
    commit(types.PROFILE_SET_RETRIEVED, null)
  })
}

// 获取用户信息
export const getUserInfo = ({ commit }) => {
  commit(types.PROFILE_SET_RETRIEVED, null)
  return request({
    url: '/yuyi-user-boot/api/sys/v1/sysUser/owner'
  }).then((res) => {
    commit(types.PROFILE_SET_RETRIEVED, res.data.data)
  }).catch(() => {
    commit(types.PROFILE_SET_RETRIEVED, null)
  })
}

// 修改密码
export const updatePassword = ({ commit }, data) => {
  const param = JSON.parse(JSON.stringify(data))
  param.oldPwd = md5(param.oldPwd + 'yuyi')
  param.newPwd = md5(param.newPwd + 'yuyi')
  return request({
    url: '/yuyi-user-boot/api/sys/v1/sysUser/updatePass',
    method: 'put',
    data: param
  }).then((res) => {
    return res
  })
}
